﻿using LayuiMvc.DataEntity.DataEntity;
using LayuiMvc.Logic.Community;
using LayuiMvcUtil.Exception;
using LayuiMvcUtil.Result;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace LayuiMvc.WebUI.Controllers
{
    public class FileController : Controller
    {
        // 文件管理业务逻辑类
        private FileService fileInstance = new FileService();


        public async Task<ActionResult> SaveFile(Guid relationGuid,string fileTag)
        {
            DataResult<string> rtnResult = new DataResult<string>();

            var savePath = Server.MapPath("~/UploadFile");
            HttpPostedFileBase file = Request.Files[0];
            if (file!=null&&!string.IsNullOrEmpty(file.FileName))
            {
                string saveFileName = Guid.NewGuid().ToString("N") + "_" + file.FileName;

                //创建文件保存实体类
                FileEntity fileEntity = new FileEntity()
                {
                    RelationGuid = relationGuid,
                    OriginalFileName = file.FileName,
                    FileType = file.ContentType,
                    FileSize = file.ContentLength * 1024,
                    UploadTime = DateTime.Now,
                    SaveFileName = saveFileName,
                    SavePath = "/UploadFile/" + saveFileName,
                    RelativeSavePath = "~/UploadFile/" + saveFileName,
                    FileTag = fileTag
                };

                //将文件保存在服务器
                file.SaveAs(Path.Combine(savePath, saveFileName));

                try
                {
                    await fileInstance.SaveFile(fileEntity);
                    rtnResult.data = fileEntity.SavePath;
                }
                catch (CustomException exception)
                {
                    rtnResult.code = 1;
                    rtnResult.msg = exception.Message;
                }
                
            }
            return Json(rtnResult);
        }
    }
}